import { defineStore } from "pinia";
import { store } from "@/store";
import { userType } from "./types";
import { routerArrays } from "@/layout/types";
import { router, resetRouter } from "@/router";
import { storageLocal } from "@pureadmin/utils";
import { Info, getInfo, getLogin } from "@/api/user";
import { useMultiTagsStoreHook } from "@/store/modules/multiTags";
import { type DataInfo, setToken, removeToken, sessionKey } from "@/utils/auth";
import { roleMy } from "@/api/system";

export const useUserStore = defineStore({
  id: "pure-user",
  state: (): userType => ({
    // 用户名
    username: storageLocal().getItem<DataInfo>(sessionKey)?.realName ?? "",
    // 页面级别权限
    roles: storageLocal().getItem<DataInfo>(sessionKey)?.roles ?? [],
    // 用户信息
    info: null
  }),
  actions: {
    /** 存储用户名 */
    SET_USERNAME(username: string) {
      this.username = username;
    },
    /** 存储角色 */
    SET_ROLES(roles: Array<string>) {
      this.roles = roles;
    },
    /**存储info */
    SET_INFO(info: Info) {
      this.info = info;
    },
    /** 登入 */
    async loginByUsername(data) {
      return new Promise((resolve, reject) => {
        getLogin(data)
          .then(data => {
            if (data.code === 0) {
              setToken(data.data);
              // 获取角色
              roleMy().then(roleResponse => {
                if (roleResponse.code === 0) {
                  const roles = roleResponse.data.map(el => el.roleKey);
                  this.SET_ROLES(roles);
                  // 获取用户信息
                  getInfo().then(res => {
                    if (res.code === 0) {
                      this.SET_INFO(res.data);
                      this.SET_USERNAME(res.data.realName);
                      // 本地存储
                      storageLocal().setItem(sessionKey, {
                        ...res.data,
                        roles
                      });
                      resolve({
                        ...res.data,
                        roles
                      });
                    }
                  });
                }
              });
            }
          })
          .catch(error => {
            reject(error);
          });
      });
    },

    /** 前端登出（不调用接口） */
    logOut() {
      this.username = "";
      this.roles = [];
      removeToken();
      useMultiTagsStoreHook().handleTags("equal", [...routerArrays]);
      resetRouter();
      router.push("/login");
    }
  }
});

export function useUserStoreHook() {
  return useUserStore(store);
}
